package com.ywb.edugui.dao.impl;

import com.alibaba.druid.util.StringUtils;
import com.ywb.edugui.dao.UserDao;
import com.ywb.edugui.entity.User;
import com.ywb.edugui.utils.MySnowflakeIdWorker;
import com.ywb.edugui.utils.SnowflakeIdWorker;
import org.apache.commons.codec.digest.DigestUtils;

import java.sql.*;
import java.util.*;

import static com.ywb.edugui.utils.JDBCUtils.getConnection;

/**
 * DaoImpl 1.0直接根据服务层接口实现对应的方法
 */

public class UserDaoImpl implements UserDao {

    private Connection conn = null;
    private PreparedStatement ps = null;
    private Statement st = null;
    private ResultSet rs = null;

    @Override
    public int add(User user) {
        int result = 0;
        if(StringUtils.isEmpty(user.getId())){
            user.setId(MySnowflakeIdWorker.nextId());
        }
//        将密码进行加密之后存入数据库
        user.setPassword(DigestUtils.md5Hex(user.getPassword()));

        try{
            conn = getConnection();
            String sql = "insert into user(id, username, password) values(?,?,?)";
            ps = conn.prepareStatement(sql);
            ps.setString(1 ,user.getId());
            ps.setString(2, user.getUsername());
            ps.setString(3, user.getPassword());
            result  = ps.executeUpdate();

        } catch (SQLIntegrityConstraintViolationException e){
            System.out.println("数据库中已存在该用户名对象");
            e.printStackTrace();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return result;
    }

    @Override
    public int delete(User user) {
        int result = 0;
        try{
            conn = getConnection();
            String sql = "delete from user where id = ?";
            ps = conn.prepareStatement(sql);
            ps.setString(1 , user.getId());
            result  = ps.executeUpdate();

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return result;
    }

    @Override
    public int delete(String id) {
        int result = 0;
        try{
            conn = getConnection();
            String sql = "delete from user where id = ?";
            ps = conn.prepareStatement(sql);
            ps.setString(1 , id);
            result  = ps.executeUpdate();

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return result;
    }

    @Override
    public int update(User user) {
        int result = 0;
        try{
            conn = getConnection();
            String sql = "update user set username = ?, password = ? where id = ?";
            ps = conn.prepareStatement(sql);
            ps.setString(1, user.getUsername());
            ps.setString(2, user.getPassword());
            ps.setString(3 ,user.getId());
            result  = ps.executeUpdate();

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return result;
    }

    /**
     * 根据Resultset返回对应的list对象,用于list(),getOne()方法
     * @param rs
     * @return
     */
    private List<User> getByRs(ResultSet rs){
        List<User> list = new ArrayList<>();
        try{
            if(rs == null || !rs.next()){
                return null;
            }
            do{
                User user = new User();
                user.setId(rs.getString("id")).setUsername(rs.getString("username")).setPassword(rs.getString("password"));
                list.add(user);
            }while(rs.next());
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }

        return list;
    }

    @Override
    public List<User> list() {
        try{
            conn = getConnection();
            String sql = "select * from user";
            st = conn.createStatement();
            rs = st.executeQuery(sql);

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return getByRs(rs);
    }

    @Override
    public User getOne(String id) {
        try{
            conn = getConnection();
            String sql = "select * from user";
            st = conn.createStatement();
            rs = st.executeQuery(sql);

        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return getByRs(rs).get(0);
    }

    @Override
    public User getByUsername(String name) {
        List<User> list = new ArrayList<>();
        try{
            conn = getConnection();
            String sql = "select * from user where username = ?";
            ps = conn.prepareStatement(sql);
            ps.setString(1, name);
//            注意使用ps的时候这里的executeQuery不能带参数，否则会把重新未处理的sql执行
            rs = ps.executeQuery();
            list = getByRs(rs);
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        }
        return list == null ? null : list.get(0);
    }


    @Override
    public Map<String, String> login(String username, String password) {
        Map<String, String> map = new HashMap<>();
        User user = getByUsername(username);
        if(user == null) {
            map.put("msg", "不存在该用户,请先注册");
        }
        else if(!user.getPassword().equals(DigestUtils.md5Hex(password))) {
            map.put("msg", "密码错误,请重新输入");
        }
        return map;
    }
}
